<template>
  <a-form-model
    ref="form"
    :model="form"
    :label-col="labelCol"
    :wrapper-col="wrapperCol"
    style="width: 400px"
    :rules="rules"
  >
    <a-form-model-item>
      <div style="text-align: center; font-size: 32px">水果店管理系统</div>
    </a-form-model-item>

    <a-form-model-item prop="username">
      <a-input v-model="form.username" placeholder="用户名">
        <a-icon slot="prefix" type="user" />
      </a-input>
    </a-form-model-item>

    <a-form-model-item prop="password">
      <a-input v-model="form.password" placeholder="密码">
        <a-icon slot="prefix" type="lock" />
      </a-input>
    </a-form-model-item>

    <a-form-model-item>
      <a-button v-if="type==='login'" type="primary" style="width: 100%" @click="onLogin">登录</a-button>
      <a-button v-if="type==='register'" type="primary" style="width: 100%" @click="onRegister">注册</a-button>
    </a-form-model-item>

    <a-form-model-item>
      <div style="text-align: right">
        <a-button v-if="type==='login'" type="link" style="padding: 0px" @click="$router.push({ name: 'register' })">注册</a-button>
        <a-button v-if="type==='register'" type="link" style="padding: 0px" @click="$router.push({ name: 'login' })">登录</a-button>
      </div>
    </a-form-model-item>
  </a-form-model>
</template>

<script>
import Vue from 'vue'
import {
  FormModel,
  Input,
  Icon,
  Button
} from 'ant-design-vue'

Vue.use(FormModel)
Vue.use(Input)
Vue.use(Icon)
Vue.use(Button)

export default {
  props: {
    type: {
      type: String,
      default () {
        return ''
      }
    }
  },

  data () {
    return {
      form: {
        username: '',
        password: ''
      },
      labelCol: { span: 0 },
      wrapperCol: { span: 24 },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: ['change', 'blur'] },
          { len: 8, message: '可输入任意字符，长度为8', trigger: ['change', 'blur'] }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: ['change', 'blur'] },
          { len: 8, message: '可输入任意字符，长度为8', trigger: ['change', 'blur'] }
        ]
      }
    }
  },

  methods: {
    onLogin () {
      this.$refs.form.validate(valid => {
        if (valid) {
          // 假设res是调登录接口成功后返回的数据，然后将其中的token和用户信息存到sessionStorage里
          const res = {
            token: 'I am token',
            username: this.form.username
          }
          window.sessionStorage.setItem('token', res.token)
          window.sessionStorage.setItem('username', res.username)
          this.$router.push({ name: 'index' })
        }
      })
    },

    onRegister () {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.$message.success('注册成功')
          this.$router.push({ name: 'login' })
        }
      })
    }
  }
}
</script>
